<script setup lang="ts">
import {ref, reactive, computed} from 'vue'
import {ElForm, ElMessage} from 'element-plus'
import {
  Collect,
  PassWord,
  PassWordLv2_1,
  PassWordLv2_2,
  PassWordLv2_3
} from '@/util/common'
import {getPublicKey, changePass, PasswordLvType} from '@/api/login'
import {IconConfig} from '@/api/config'
import Jsencrypt from 'jsencrypt'

import dIcon from '@/components/dIcon.vue'
import dDialog from '@/components/dDialog/dDialog.vue'
import passwordLv from '@/components/passwordLv.vue'
import router from '@/router'

defineProps({
  showPasswordDialog: {
    type: Boolean,
    required: true
  }
})

const emits = defineEmits(['close'])

const onClose = () => {
  emits('close')
}

type FormInstance = InstanceType<typeof ElForm>
const encrypt = new Jsencrypt()
const showPassWordOld = ref(false)
const showPassWordNew = ref(false)
const showPassWordFim = ref(false)

//表单数据
const loginForm = reactive({
  passwordOld: '',
  passwordNew: '',
  passwordFim: ''
})

const checkValidatePass = (_rule, value: string, callback) => {
  if (value === '') {
    callback(new Error('请再次确认密码'))
  } else if (value !== loginForm.passwordNew) {
    callback(new Error('两次密码不一致！'))
  } else {
    callback()
  }
}

const rules = reactive({
  passwordOld: [
    {required: true, message: '请输入原始密码', trigger: ['change', 'blur']},
    {
      required: true,
      message: '密码应是字母、数字、@、#、$、%、^、* 、_',
      pattern: Collect,
      trigger: ['change', 'blur']
    },
    {
      required: true,
      message: '密码必须包含大小写字母、数字以及特殊符号',
      pattern: PassWord,
      trigger: ['change', 'blur']
    },
    {
      required: true,
      message: '密码长度应为8-32位',
      min: 8,
      max: 32,
      trigger: ['change', 'blur']
    }
  ],
  passwordNew: [
    {required: true, message: '请输入新密码', trigger: ['change', 'blur']},
    {
      required: true,
      message: '密码应是字母、数字、@、#、$、%、^、* 、_',
      pattern: Collect,
      trigger: ['change', 'blur']
    },
    {
      required: true,
      message: '密码必须包含大小写字母、数字以及特殊符号',
      pattern: PassWord,
      trigger: ['change', 'blur']
    },
    {
      required: true,
      message: '密码长度应为8-32位',
      min: 8,
      max: 32,
      trigger: ['change', 'blur']
    }
  ],
  passwordFim: [
    {required: true, validator: checkValidatePass, trigger: ['change', 'blur']}
  ]
})

const showIcon: IconConfig = {
  icon: 'login-password-show',
  type: 'custom',
  size: 24
}
const hideIcon: IconConfig = {
  icon: 'login-password-hide',
  type: 'custom',
  size: 24
}

const loginFormRef = ref<FormInstance>()

const onChange = (prop: string) => {
  if (prop === 'old') {
    showPassWordOld.value = !showPassWordOld.value
  } else if (prop === 'new') {
    showPassWordNew.value = !showPassWordNew.value
  } else if (prop === 'fim') {
    showPassWordFim.value = !showPassWordFim.value
  }
}

//获取密码
const getPassword = (publicKey: string, _password: string): Promise<string> => {
  return new Promise((resolve, reject) => {
    encrypt.setPublicKey(publicKey)
    const password = encrypt.encrypt(_password)
    if (password) {
      resolve(password)
    } else {
      reject('加密失败')
    }
  })
}

const showLoading = ref(false)
//表单验证
const onSubmit = () => {
  const elForm = loginFormRef.value
  if (!elForm) return
  elForm.validate((valid) => {
    if (valid) {
      let oldPass = ''
      let newPass = ''
      let key = ''
      showLoading.value = true
      getPublicKey()
        .then((res) => {
          key = res.data.data
          return getPassword(key, loginForm.passwordOld)
        })
        .then((_oldPass: string) => {
          oldPass = _oldPass
          return getPassword(key, loginForm.passwordNew)
        })
        .then((_newPass: string) => {
          newPass = _newPass
          return changePass({oldPass: oldPass, newPass: newPass})
        })
        .then(() => {
          ElMessage.success('修改密码成功')
          showLoading.value = false
          onClose()
          router.push({name:'Login'})
        })
        .catch((error) => {
          console.warn(error)
          showLoading.value = false
        })
    } else {
      return false
    }
  })
}

//密码强度
const getPasswordLv = computed<PasswordLvType>(() => {
  const password = loginForm.passwordNew
  if (password.length < 8) {
    return 1
  } else if (PassWord.test(password)) {
    return 3
  } else if (
    PassWordLv2_1.test(password) ||
    PassWordLv2_2.test(password) ||
    PassWordLv2_3.test(password)
  ) {
    return 2
  } else {
    return 1
  }
})

const onConfirm = () => {
  onSubmit()
}
</script>

<template>
  <d-dialog
    custom-class="login-changepw"
    title="修改密码"
    :width="680"
    :show-dialog="showPasswordDialog"
    :show-save-loading="showLoading"
    @cancel="onClose"
    @confirm="onConfirm"
    @close="onClose"
  >
    <div class="wapper">
      <el-form
        ref="loginFormRef"
        class="from-login"
        :rules="rules"
        :model="loginForm"
        label-position="right"
        :label-width="80"
        @keyup.enter="onSubmit()"
      >
        <el-form-item prop="passwordOld" label="原密码">
          <el-input
            v-model="loginForm.passwordOld"
            clearable
            :type="showPassWordOld ? undefined : 'password'"
            autocomplete="current-password"
            placeholder="请输入原始密码"
            :style="{width: '430px', height: '32px', borderRadius: '4px'}"
          >
            <template #suffix>
              <dIcon
                class="d-common-icon-theme"
                :icon-config="showPassWordOld ? hideIcon : showIcon"
                @click="onChange('old')"
              />
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="passwordNew" label="新密码">
          <el-input
            v-model="loginForm.passwordNew"
            clearable
            :type="showPassWordNew ? undefined : 'password'"
            autocomplete="new-password"
            placeholder="请输入新密码"
            :style="{width: '430px', height: '32px', borderRadius: '4px'}"
          >
            <template #suffix>
              <dIcon
                class="d-common-icon-theme"
                :icon-config="showPassWordNew ? hideIcon : showIcon"
                @click="onChange('new')"
              />
            </template>
          </el-input>
        </el-form-item>
        <div class="inforwapper">
          <div class="d-common-flex-row">
            <span class="infor-lv">密码强度：</span>
            <password-lv :lv="getPasswordLv" />
          </div>
          <div class="infor-lv" style="marginbottom: 15px">
            密码包含：8-32位，大小写字母、数字以及特殊符号（@、#、$、%、^、*、_）
          </div>
        </div>
        <el-form-item prop="passwordFim" label="确认密码">
          <el-input
            v-model="loginForm.passwordFim"
            clearable
            :type="showPassWordFim ? undefined : 'password'"
            autocomplete="new-password"
            placeholder="请再次确认密码"
            :style="{width: '430px', height: '32px', borderRadius: '4px'}"
          >
            <template #suffix>
              <dIcon
                class="d-common-icon-theme"
                :icon-config="showPassWordFim ? hideIcon : showIcon"
                @click="onChange('fim')"
              />
            </template>
          </el-input>
        </el-form-item>
      </el-form>
    </div>
  </d-dialog>
</template>

<style scoped>
.wapper {
  width: 100%;
  padding: 30px 0;
}
.from-login {
  padding-left: 56px;
}
.infor-lv {
  color: var(--d-font-color-tab);
  font-size: 12px;
}
.inforwapper {
  padding-left: 85px;
}
</style>
